package server;

import java.io.*;

public class User implements UserInterface {
	private String name;
	private String[] friends;
	
	public static int MAX_FRIENDS = 10;

	public User(String name, String friends[]) {
		this.name = name; 
		this.friends = friends;
	}

	public User(String name) {
		this.name = name;
		try {
			this.updateFriendsFromFile(new File(this.name + ".txt"));
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)
	 * @see server.UserInterface#getFriends()
	 */
	public String[] getFriends() throws Throwable {
		this.updateFriendsFromFile(new File(this.name + ".txt"));
		return this.friends;
	}

	/* (non-Javadoc)
	 * @see server.UserInterface#getName()
	 */
	public String getName() {
		return this.name;
	}

	private void updateFriendsFromFile(File file) throws Throwable {
		String tempList[] = new String[User.MAX_FRIENDS];
		BufferedReader b;
		String s = "";
		
		try {
			b = new BufferedReader(new FileReader(file));
			for (int i = 0; i < User.MAX_FRIENDS; i++) {
				if ((s = b.readLine()) == null) {
					break;
				}
				else {
					tempList[i] = s;
				}
			}
			b.close();
		} catch (FileNotFoundException e) {
			file.createNewFile();				
			e.printStackTrace();
		}
		
		this.friends = tempList;
	}

	public boolean appendFriend(String friend) {
		try {
			File file = new File(this.getName() + ".txt");
			
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
			bufferedWriter.write(friend + "\n");
			bufferedWriter.flush();
			bufferedWriter.close();
			return true;
		} catch (Throwable ioe) {
			ioe.printStackTrace();
			return false;
		}
	}
}
